package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.dubbo.api.AudioApi;
import com.tanhua.dubbo.api.RecommendUserApi;
import com.tanhua.dubbo.pojo.Audio;
import com.tanhua.dubbo.pojo.RecommendUser;
import com.tanhua.dubbo.pojo.UserInfo;
import com.tanhua.server.vo.AudioVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Collections;
import java.util.List;

@Service
@Slf4j
public class AudioService {

    @DubboReference(version = "1.0.0")
    private AudioApi audioApi;

    @Autowired
    private UserInfoService userInfoService;

    @DubboReference(version = "1.0.0")
    private RecommendUserApi recommendUserApi;

    @Autowired
    protected FastFileStorageClient storageClient;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * @param audioFile
     * @return
     */
    public Boolean saveAudio(MultipartFile audioFile) {
        Long userId = UserThreadLocal.get();

        Audio audio = new Audio();
        audio.setUserId(userId);
        try {

            //上传音频
            StorePath storePath = storageClient.uploadFile(audioFile.getInputStream(),
                    audioFile.getSize(),
                    StrUtil.subAfter(audioFile.getOriginalFilename(), '.', true),
                    null);
            //设置音频url
            audio.setAudioUrl(fdfsWebServer.getWebServerUrl() + storePath.getFullPath());

            String uploadAudio = this.audioApi.uploadAudio(audio);
            return StrUtil.isNotEmpty(uploadAudio);
        } catch (Exception e) {
            log.error("发布音频失败！file = " + audioFile.getOriginalFilename(), e);
        }

        return false;
    }

    /*public AudioVo queryAudio() {
        Long userId = UserThreadLocal.get();
        AudioVo audioVo = new AudioVo();
        Audio audio = audioApi.queryAudioById(userId);
        if (ObjectUtil.isEmpty(audio)) {
            return null;
        }
        UserInfo userInfo = userInfoService.queryUserInfoByUserId(audio.getUserId());
        Integer remainingTimes = audioApi.getRemainingTimes(userId);
        audioVo.setSoundUrl(audio.getAudioUrl());
        audioVo.setUserId(userInfo.getUserId());
        audioVo.setNickname(userInfo.getNickName());
        audioVo.setAge(userInfo.getAge());
        audioVo.setAvatar(userInfo.getLogo());
        audioVo.setGender(userInfo.getSex().getValue() == 1 ? "men" : "women");
        audioVo.setRemainingTimes(remainingTimes);
        return audioVo;
    }*/

    public AudioVo queryAudio() {
        Long userId = UserThreadLocal.get();
        AudioVo audioVo = new AudioVo();
        List<RecommendUser> recommendUserList = this.recommendUserApi.queryCardList(userId, 99);

        if (CollUtil.isEmpty(recommendUserList)) {
            return null;
        }
        Collections.shuffle(recommendUserList);

        RecommendUser recommendUser;
        List<Audio> audioList;
        int count = 0;
        while (true) {
            recommendUser = recommendUserList.get(count);
            count++;
            audioList = this.audioApi.queryAudioById(recommendUser.getUserId());
            if (CollUtil.isNotEmpty(audioList)) {
                // 查询一次，可查询持续减一
                String redisKey = "REMAINING_TIMES";
                String hashCountKey = "COUNT_" + userId.toString();
                redisTemplate.opsForHash().increment(redisKey, hashCountKey, -1);
                break;
            }
            if (count >= recommendUserList.size()) {
                return null;
            }
        }

        Audio audio = audioList.get(RandomUtil.randomInt(audioList.size()));
        UserInfo userInfo = userInfoService.queryUserInfoByUserId(audio.getUserId());

        audioVo.setSoundUrl(audio.getAudioUrl());
        audioVo.setUserId(userInfo.getUserId());
        audioVo.setNickname(userInfo.getNickName());
        audioVo.setAge(userInfo.getAge());
        audioVo.setAvatar(userInfo.getLogo());
        audioVo.setGender(userInfo.getSex().getValue() == 1 ? "men" : "women");
        Integer remainingTimes = audioApi.getRemainingTimes(userId);
        audioVo.setRemainingTimes(remainingTimes);

        return audioVo;
    }


}
